package com.iwunu.auth.init;

import com.iwunu.auth.config.JwtConfig;
import com.iwunu.auth.filter.JWTAuthenticationFilter;
import com.iwunu.auth.filter.JWTLoginFilter;
import com.iwunu.auth.util.DigestsUtils;
import com.iwunu.auth.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 安全配置初始化
 * @author vivi207
 *
 */
@Configuration
@Order(SecurityProperties.BASIC_AUTH_ORDER)
public class WebSecurityInit extends WebSecurityConfigurerAdapter  {
	private static final Logger LOGGER = LoggerFactory.getLogger(WebSecurityInit.class);

	private UserDetailsService userDetailsService;
	private BCryptPasswordEncoder bCryptPasswordEncoder;

	@Autowired
	private JwtConfig jwtConfig;
	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	public WebSecurityInit(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
		this.userDetailsService = userDetailsService;
		this.bCryptPasswordEncoder = bCryptPasswordEncoder;
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		LOGGER.info("web security jwt configure, permitAll：{}", jwtConfig.getPermitAll());

		String[] permitAlls = jwtConfig.getPermitAll().split(",");
		http.cors()
			.and()
				.csrf().disable();
		if(permitAlls!=null && permitAlls.length>0 && !"".equals(jwtConfig.getPermitAll())) {
			http.authorizeRequests().antMatchers(permitAlls).permitAll()
				.anyRequest().authenticated();
		}else {
			http.authorizeRequests().anyRequest().authenticated();
		}

		http.authorizeRequests()
				.and()
				.addFilter(new JWTLoginFilter(authenticationManager(), jwtTokenUtil))
				.addFilter(new JWTAuthenticationFilter(authenticationManager(), jwtTokenUtil));
	}

	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth
			.userDetailsService(userDetailsService)
			.passwordEncoder(new PasswordEncoder() {
				@Override
				public String encode(CharSequence rawPassword) {
					return DigestsUtils.entryptPassword((String) rawPassword);
				}

				@Override
				public boolean matches(CharSequence rawPassword, String encodedPassword) {
					return DigestsUtils.validatePassword((String) rawPassword, encodedPassword);
				}
			});
	}
}
